#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# This Checks creates one PNP Graph for each Processor.
# Just place it in your local/share/check_mk/checks

winperf_cpu_default_levels = {"levels": (101.0, 101.0)}


def inventory_winperf_single(info):
    if len(info) <= 1:
        return None

    for line in info[1:]:
        if line[0] == '-232':
            return [(None, "winperf_cpu_default_levels")]


# params: levels for warn / crit in percentage
def check_winperf_single(_no_item, params, info):
    if not info:
        return
    this_time = int(float(info[0][0]))

    for line in info[1:]:
        if line[0] == '-232':
            num_cpus = len(line) - 2
            for cpu in range(1, num_cpus):
                ticks = int(line[cpu])
                ticks_per_sec = get_rate("winperf_single_" + str(cpu), this_time, ticks)
                cpusecs_per_sec = ticks_per_sec / 10000000.0
                used_perc = 100.0 * (1 - cpusecs_per_sec)

                # Due to timeing invariancies the measured level can become > 100%.
                # This makes users unhappy, so cut it off.
                if used_perc < 0:
                    used_perc = 0
                elif used_perc > 100:
                    used_perc = 100

                #state, infotext, perfdata = check_cpu_single(used_perc, params, this_time)
                perfdata = [("CPU%s" % cpu, used_perc)]
                infotext = "CPU%s: %d %%" % (cpu, used_perc)
                yield 0, infotext, perfdata


check_info["winperf_processor.single"] = {
    'check_function': check_winperf_single,
    'inventory_function': inventory_winperf_single,
    'service_description': 'CPU utilization single',
    'has_perfdata': True,
    'group': 'cpu_utilization_os',
    #'includes':                [ "cpu_single.include" ],
}
